package com.cgt.day25;

import org.junit.Test;

import java.lang.reflect.Field;

public class Reflect2Demo {
	@Test
	public void test1() throws IllegalAccessException {
		Teacher teacher = new Teacher();
		System.out.println(teacher);
		changeField(teacher);
		System.out.println(teacher);

//		Student student = new Student();
//		student.setName("lisia");
//		System.out.println(student);
//		changeField(student);
//		System.out.println(student);
	}

	private void changeField(Object object) throws IllegalAccessException {
		//1.获得对应的Class
		Class clazz = object.getClass();
		//2.获取所有的Field[] fields
		Field[] fields = clazz.getDeclaredFields();
		//3.遍历所有的Field，如果是String类型，将包含的a改成b
		for (Field field : fields) {
			//3.1 如果是String类型才修改
			if (field.getType() == String.class) {
				//属性是私有的
				field.setAccessible(true);
				//student.getName(); 并不是调用getName，因为调用getName()要拿到对应method
				//student.name
				//3.2或者Field原来的值  "qingdao"
				String oldValue = (String) field.get(object);
				if (oldValue != null && !"".equals(oldValue)) {
					String newValue = oldValue.replace("a", "b");
					//3.3将修改后的值设置到Field
					field.set(object, newValue);
				}
			}
		}
	}
}
